package com.dullong.firedocmanager.Controller.page;

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.dullong.firedocmanager.bean.PDocument;
import com.dullong.firedocmanager.lucene4.LuceneSearchService;

@Controller
public class SearchPage {

	@Autowired
	LuceneSearchService luceneSearchService;

	@RequestMapping(value = "/search.html", method = RequestMethod.GET)
	public ModelAndView searchPage(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "keyword", required = false) String title_keyword,
			@RequestParam(value = "body_keyword", required = false) String body_keyword,
			@RequestParam(value = "title_body", required = false) Integer title_body,
			@RequestParam(value = "uploadtimeF", required = false) Long uploadtimeF,
			@RequestParam(value = "uploadtimeT", required = false) Long uploadtimeT,
			@RequestParam(value = "types", required = false) String[] types,
			@RequestParam(value = "cates", required = false) Integer[] cates,
			@RequestParam(value = "roleids", required = false) Integer[] roleids,
			@RequestParam(value = "page", required = false) Long page,
			@RequestParam(value = "limit", required = false) Long limit)
			throws IOException {

		page = page == null ? 1 : page;
		limit = limit == null || limit < 0 ? 10 : limit;
		title_body = title_body == null ? 0 : title_body;
		uploadtimeF = uploadtimeF == null ? Long.MIN_VALUE : uploadtimeF;
		uploadtimeT = uploadtimeT == null ? Long.MAX_VALUE : uploadtimeT;
		body_keyword = StringUtils.isEmpty(body_keyword) ? title_keyword
				: body_keyword;

		ModelAndView view = new ModelAndView();
		if (null == title_keyword) {
			view.setViewName("search-home");
		} else {
			PDocument pDocument = luceneSearchService.search(title_keyword,
					body_keyword, title_body, uploadtimeF, uploadtimeT, types,
					cates, roleids, page, limit);
			if (pDocument == null) {
				view.setViewName("search-home");
			} else {
				view.addObject("pDocument", pDocument);
				view.setViewName("search-page");
			}
		}
		return view;
	}

}
